# !/usr/bin/env python
# -*- coding:utf-8 -*-

import logging
# 导入PyQt6
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QDialog

from view.mv_tree import Ui_mv
from service.tishi_service import Tishi

# ==============================================================================
# view 10.用例批量移动，模块选择页面
# ==============================================================================


class Mv_Tree(QDialog, Ui_mv):
    """模块选择页面"""
    confirmed_signal_mv = pyqtSignal()

    def __init__(self, case_db, caseid=None, parent=None):
        super().__init__(parent)
        self.setupUi(self)  # 直接调用self的setupUi方法
        self.ts = Tishi()
        self.case_db = case_db
        self.case_db.connect()
        self.caseid = caseid

        self.bc.setAutoDefault(False)  # 取消回车激活按钮
        self.qx.setAutoDefault(False)  # 取消回车激活按钮
        self.chaxun_mk()

    def chaxun_mk(self):
        """模糊查询模块名称，只能查询根、1级模块"""
        value = ['%' + self.chaxun1.text() + '%']
        row = self.case_db.query_many(f"select modulename,moduleid from module where modulename like ? and status = 10",
                                      value)
        row.reverse()
        self.mk_mv.clear()  # 清空下拉框
        for parent_name in row:
            self.mk_mv.addItem(parent_name[0] + '—ID:' + str(parent_name[1]))
        logging.info('模糊查询模块名称，查询根、1级模块')

    def mv_yongli(self):
        """用例批量移动"""
        parts = self.mk_mv.currentText().split("—ID:")
        if len(parts) == 2:
            mk_id = parts[1]
            if len(self.caseid) == 1:
                sql = f"update main.testcase set moduleid=? where caseid = {self.caseid[0]}"
            else:
                sql = f"update main.testcase set moduleid=? where caseid in {self.caseid}"
            if self.case_db.operate_one(sql, (mk_id,)):
                self.close()
            else:
                self.ts.xinxi("出错了")
        else:
            self.ts.xinxi("选择移动到的模块")

    def closeEvent(self, QCloseEvent):
        """窗口关闭时关闭数据库"""
        self.confirmed_signal_mv.emit()  # 发射查询信号
        self.case_db.over()  # 关闭游标
        logging.info("[批量移动页面，游标关闭]")
